<template>
    <toolbar :editor="editorRef" :defaultConfig="toolbarConfig" :mode="mode" style="border-bottom: 1px solid #ccc" />
    <editor :defaultConfig="editorConfig" :mode="mode" v-model="valueHtml" style="height: 300px; overflow-y: hidden"
        @onCreated="handleCreated" @onChange="handleChange" />
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css'
import { onBeforeUnmount, ref, shallowRef, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'

const emit = defineEmits(['updateEditorEvent'])
const props = defineProps(['content'])

// 编辑器实例，必须用 shallowRef，重要！
const editorRef = shallowRef()
const mode = ref('default')
// 内容 HTML
const valueHtml = ref('')

const toolbarConfig = {}
const editorConfig = { placeholder: '请输入内容...' }
// 编辑器回调函数
const handleCreated = (editor) => {
    console.log('created', editor);
    editorRef.value = editor; // 记录 editor 实例，重要！
    valueHtml.value = props.content || ''
}

const handleChange = (editor) => {
    // console.log('change:', editor.getHtml());
    emit('updateEditorEvent', editor.getHtml())
}

// 父传子的文本内容如果放在onMounted中赋值会失效，原因是onMounted会早于handleCreated执行
// onMounted(() => valueHtml.value = props.content || '')

// 组件销毁时，也及时销毁编辑器，重要！
onBeforeUnmount(() => {
    const editor = editorRef.value;
    if (editor == null) return;

    editor.destroy();
});
</script>